package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.UnLikeBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.UnLikesBehaviorService;
import com.usian.model.behavior.dtos.UnLikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApUnlikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UnLikesBehaviorServiceImpl extends ServiceImpl<UnLikeBehaviorMapper, ApUnlikesBehavior> implements UnLikesBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;


    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        //1.检查参数
        if(dto == null || dto.getArticleId() == null || (dto.getType() < 0 && dto.getType() > 2)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if(apBehaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //3.点击不喜欢和喜欢
        ApUnlikesBehavior unlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()).eq(ApUnlikesBehavior::getEntryId, user.getId()));
        if (unlikesBehavior == null){
            unlikesBehavior = new ApUnlikesBehavior();
            unlikesBehavior.setArticleId(dto.getArticleId());
            unlikesBehavior.setEntryId(apBehaviorEntry.getId());
            unlikesBehavior.setType((int)dto.getType());
            unlikesBehavior.setCreatedTime(new Date());
            save(unlikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            //否则行为实体关注了作者用户，则根据用户id修改关注的行为
            unlikesBehavior.setType((int)dto.getType());
            updateById(unlikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
